# application/services/detection/product.py
from application.mapper.detection.product import ProductMapper
from typing import Dict, Any, List, Tuple
from application.models.detection.product import Product
from application.utils.res import models_to_dicts_camel, rows_to_dicts_camel, to_snake_case, convert_keys_to_camel


class ProductService:
    """产品服务层"""

    @staticmethod
    def get_product_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> Tuple[List[Dict[str, Any]], int]:
        """
        分页获取产品数据列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: (产品数据列表, 总数)
        """
        product_list, total = ProductMapper.get_product_list(
            page_num, page_size, conditions
        )

        result_list = models_to_dicts_camel(product_list)

        return result_list, total

    @staticmethod
    def get_product_optionselect() -> List[Dict[str, Any]]:
        """
        获取产品下拉列表
        :return: 产品列表
        """
        products = ProductMapper.get_all_products()
        result_list = convert_keys_to_camel(products)
        result_list = rows_to_dicts_camel(result_list)
        return result_list

    @staticmethod
    def create_product(product_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建产品
        :param product_data: 产品数据
        :return: 创建后的产品数据
        """
        # 创建产品对象
        product = Product()

        for key, value in product_data.items():
            snake_key = to_snake_case(key)
            if hasattr(product, snake_key):
                setattr(product, snake_key, value)
        
        created_product = ProductMapper.create_product(product)
        return models_to_dicts_camel([created_product])[0]

    @staticmethod
    def update_product(product_id: int, product_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        更新产品
        :param product_id: 产品ID
        :param product_data: 产品数据
        :return: 更新后的产品数据
        """
        product = ProductMapper.get_product_by_id(product_id)
        
        if not product:
            return None
            
        # 更新产品对象
        for key, value in product_data.items():
            snake_key = to_snake_case(key)
            if hasattr(product, snake_key):
                setattr(product, snake_key, value)
        
        updated_product = ProductMapper.update_product(product)
        return models_to_dicts_camel([updated_product])[0]

    @staticmethod
    def delete_product(product_id: int) -> bool:
        """
        删除产品
        :param product_id: 产品ID
        :return: 删除结果 True/False
        """
        product = ProductMapper.get_product_by_id(product_id)
        
        if not product:
            return False
            
        try:
            ProductMapper.delete_product(product)
            return True
        except Exception:
            return False